package me.zhengjie.modules.fileupload.rest;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.fileupload.domain.ElectronicMaterialFileDetailVO;
import me.zhengjie.modules.fileupload.domain.ElectronicMaterialFileVO;
import me.zhengjie.modules.fileupload.domain.Result;
import me.zhengjie.modules.fileupload.domain.dto.ElectronicMaterialFileDetailVOCriteria;
import me.zhengjie.modules.fileupload.service.ElectronicMaterialService;
import me.zhengjie.tool.ValidateUtil;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.vo.Constant;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

@RestController
@RequiredArgsConstructor
@Api(tags = "api")
@RequestMapping("/api/electronic-material")
public class FileUploadController {

    @Resource
    private ElectronicMaterialService electronicMaterialService;

    /**
     * 查询电子材料列表
     */
    @GetMapping("/list")
    public ResponseEntity<PageResult<ElectronicMaterialFileDetailVO>> list(ElectronicMaterialFileDetailVOCriteria criteria) throws IOException {
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> param = objectMapper.convertValue(criteria, Map.class);
        return new ResponseEntity<>(electronicMaterialService.queryList(param, page), HttpStatus.OK);
    }

    /**
     * 查询电子材料base64
     */
    @PostMapping("/getBase64")
    public ResponseEntity<String> getFileAsBase64(@RequestBody Map param) throws IOException {
        ValidateUtil.isEmptyThrowException(param.get("filename"),"文件名称");
        ValidateUtil.isEmptyThrowException(param.get("aae036_yw"),"文件创建时间");
        String filename = param.get("filename").toString();
        String aae036 =  param.get("aae036_yw").toString();
        Path filePath = Paths.get(Constant.UPLOAD_DIR + "/" + aae036 + "/").resolve(filename);
        byte[] fileContent = Files.readAllBytes(filePath);
        String base64 = Base64.getEncoder().encodeToString(fileContent);
        String mimeType = Files.probeContentType(filePath);

        return ResponseEntity.ok("data:" + mimeType + ";base64," + base64);
    }

    /**
     * 删除材料
     */
    @PostMapping("/deleteFile")
    public ResponseEntity<String> deleteFile(@RequestBody Map param) throws IOException {
        ValidateUtil.isEmptyThrowException(param.get("id"),"材料id");
        electronicMaterialService.deleteFile(param.get("id").toString());
        return ResponseEntity.ok("成功");
    }

    /**
     * 上传电子材料
     */
    @PostMapping("/upload")
    public Result upload(
            @RequestParam("aac001") String aac001,
            @RequestParam("aaa121") String aaa121,
            @RequestParam("name") String name,
            @RequestParam("id") String id,
            @RequestParam("file") MultipartFile[] files) {

        try {
            ElectronicMaterialFileVO fileVO = null;
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    fileVO = electronicMaterialService.uploadFile(
                            aac001, aaa121, name, id, file);
                }
            }
            return Result.success(fileVO);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 下载电子材料文件
     */
//    @GetMapping("/download/{fileId}")
//    public void download(@PathVariable String fileId, HttpServletResponse response) {
//        electronicMaterialService.downloadFile(fileId, response);
//    }
}
